﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Kokomo.Environment.Hosting.Settings;
using Kokomo.Environment.Services;

namespace Kokomo.Environment.Hosting.Services
{
	class SettingsManager : ServiceObjectBase, ISettingsManager
	{
		public SettingsManager(EditorApplication editorApplication)
			: base(editorApplication)
		{
			this.SettingsObjects = new CachedLookupTable<Type, SettingsBase>(this.CreateSettings);

			this.CheckRecovery();
		}

		private void CheckRecovery()
		{
			GeneralSettings general = this.GetSettings<GeneralSettings>();
			general.StartupRecovery = general.IsInStartup;
			general.IsInStartup = true;
			general.Save();
		}

		protected IDictionary<Type, SettingsBase> SettingsObjects { get; private set; }

		private SettingsBase CreateSettings(Type key)
		{
			SettingsBase settings = (SettingsBase)Activator.CreateInstance(key, true);
			{
				ApplicationSettingsBase appSettings = settings as ApplicationSettingsBase;
				if (appSettings != null)
				{
					appSettings.Upgrade();
				}
			}
			return settings;
		}

		public TSettings GetSettings<TSettings>()
			where TSettings : SettingsBase, new()
		{
			SettingsBase settings = this.SettingsObjects[typeof(TSettings)];
			return (TSettings)settings;
		}

		public void SaveAllSettings()
		{
			foreach (var settingsEntry in this.SettingsObjects)
			{
				settingsEntry.Value.Save();
			}
		}
	}
}
